// 原始数据项的接口
interface DataItem {
  id: string;
  parentId?: string;
  data: Record<string, unknown>;
  name: string;
  remark?: string;
  [key: string]: unknown; // 允许其他属性
}

// 带 children 的数据项接口
interface DataItemWithChildren extends DataItem {
  children: DataItemWithChildren[];
}

// Antd Tree 节点接口
interface TreeNode {
  id: string;
  title: string;
  key: string;
  isLeaf: boolean;
  remark?: string;
  data: DataItemWithChildren;
  children?: TreeNode[];
}

// id -> item 映射接口
interface ItemMap {
  [key: string]: DataItemWithChildren;
  [key: number]: DataItemWithChildren;
}

export const arrToTree = (data: DataItem[]): TreeNode[] => {
  // Step 1: 构建 id -> item 映射
  const map: ItemMap = {};
  const tree: DataItemWithChildren[] = [];

  data.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  // Step 2: 构建树结构
  data.forEach(item => {
    const node = map[item.id];
    if (item.parentId && map[item.parentId]) {
      map[item.parentId].children.push(node);
    } else {
      tree.push(node);
    }
  });

  // Step 3: 转为 Antd Tree 结构（带 title、key、isLeaf）
  const convertToTreeNode = (nodes: DataItemWithChildren[], _path: string = '0-0'): TreeNode[] =>
    nodes.map((node, _index) => {
      // const key = `${path}-${index}`;
      const key = node.id;
      const children = node.children?.length ? convertToTreeNode(node.children, String(key)) : [];

      return {
        title: node.name,
        key,
        isLeaf: children.length === 0,
        remark: node.remark,
        data: node,
        children: children.length > 0 ? children : undefined,
      };
    });

  return convertToTreeNode(tree);
};

// // 使用示例
// const sampleData: DataItem[] = [
// 	{ id: 1, name: '文件夹1', remark: '这是文件夹1' },
// 	{ id: 2, parentId: 1, name: '子文件夹1', remark: '这是子文件夹1' },
// 	{ id: 3, parentId: 1, name: '子文件夹2' },
// 	{ id: 4, parentId: 2, name: '文件1.txt' },
// 	{ id: 5, name: '文件夹2' },
// 	{ id: 6, parentId: 5, name: '文件2.txt' }
// ];

// const treeData = arrToTree(sampleData);
// console.log('多个平行的一级节点：');
// console.log(JSON.stringify(treeData, null, 2));
